package docmanager.operation.ejemplos;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import bf.operation.Operation;
import bf.operation.OperationException;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import docmanager.db.ConfigData;



public class OpSubirArchivo2 extends Operation {

	@Override
	public Map execute(HttpServletRequest request) throws OperationException {
		Map m;
		m = new HashMap();
		// TODO Auto-generated method stub
		List /* FileItem */ items = this.getObjetosMultipart();
		System.out.println("Hay " + items.size() + " objetos a procesar.");
// Por algun motivo aquI llegan cero objetos. Sera que se agota por lo hecho antes?
		Iterator it = items.iterator();
		// Indicacion de almacenamiento.
		//String path = request.getSession().getServletContext().getRealPath("/");
		String path = ConfigData.getInstance().getTempPath();
		System.out.println("Almacenaremos en " + path);
		// Process the uploaded items
		Iterator iter = items.iterator();
		while (iter.hasNext()) 
		{
		   FileItem item = (FileItem) iter.next();
		   System.out.println("Procesando campo " + item.getFieldName());
		   if (item.isFormField()) 
		   {
		       // processFormField(item);
		   } else if ("archivo".equals(item.getFieldName()))
		   {
		    		File fullFile  = new File(item.getName());
		    		System.out.println("Recibiendo " + fullFile);
		    		File savedFile = new File(path, fullFile.getName());
		    		System.out.println("Almacenando en " + savedFile.getAbsolutePath());
		    		try {
					item.write(savedFile);
		    		} catch (Exception e) {
					// TODO Auto-generated catch block
						e.printStackTrace();
						throw new OperationException();
		    		}
		    }
 
		}
			   		
		return m;
	}

	@Override
	public String getReturnURL() {
		// TODO Auto-generated method stub
		return "Main.jsp";
	}

}
